package org.igeek.atomqq.net;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 * 全局cookie管理器
 * @author 作者 E-mail:hangxin1940@gmail.com
 * @version 创建时间：2011-7-22 下午02:55:21
 */
public class  CookieManager {
	private HashMap<String,String> cookies;
	
	/**
	 * 初始化cookie管理器
	 */
	public synchronized static CookieManager getInstance(){
		
		return new CookieManager();
		
	}
	
	private CookieManager(){
		cookies=new HashMap<String, String>();
	}
	
	
	/**
	 * 获得指定的cookie值
	 * @param key
	 * @return
	 */
	public String getCookieValue(String key){
		
		String value="";
		value=cookies.get(key);
		return value;
	}
	
	/**
	 * 存储一个cookie
	 * @param key
	 * @param value
	 */
	public void addCookie(String key,String value){
		cookies.put(key, value);
	}
	
	/**
	 * 讲一个字符串形式的cookie集合存储
	 * @param cookies
	 */
	public synchronized void  setCookies(List<String> cookies){
		if(cookies!=null){
			for(String co:cookies){
				String cookie=co.substring(0, co.indexOf("; "));
				int split=cookie.indexOf("=");
				String key=cookie.substring(0, split);
				String value=cookie.substring(split+1);
				addCookie(key, value);
			}
		}
		
	}
	
	public synchronized  void setCookies(String cookies){
		if(cookies!=null){
			String[] cookie=cookies.split("; ");
			for(String cook:cookie){
				int split=cook.indexOf("=");
				String key=cook.substring(0, split);
				String value=cook.substring(split+1);
				addCookie(key, value);
			}
		}
	}
	/**
	 * 以字符串形式返回所有cookie
	 * @return
	 */
	public String getCookies(){
		StringBuffer sb=new StringBuffer();
		for(Entry<String, String> cookie:cookies.entrySet()){
			String key=cookie.getKey();
			String value=cookie.getValue();
			if(value!=null&&(!"".equals(value)))
				sb.append(key+"="+value+"; ");
		}
		return sb.toString();
	}
	
	/**
	 * 把value为空的cookies清空
	 */
	public void clearCookies() {
		cookies.clear();
		
	}

}
